<template>
    <a-modal
        v-model:visible="showModal"
        :title="title"
        :width="520"
        :destroyOnClose="true"
        :maskClosable="false"
        :confirmLoading="loading"
        @ok="onSubmit"
        @cancel="handleCancle"
    >
        <a-form class="dict-model" layout="horizontal" :model="detail" :rules="rules" ref="formRef">
            <a-form-item :label="t('yl.name')" class="full-width" name="typeName">
                <a-input v-model:value="detail.typeName" />
            </a-form-item>
        </a-form>
    </a-modal>
</template>
<script lang="ts">
import { computed, defineComponent, reactive, ref, toRefs, watch } from 'vue';
import { useI18n } from 'vue-i18n';

// 表单校验规则
const initRules = (t: fn) => {
    return {
        typeName: [{ required: true, message: t('yl.inputValueStand'), trigger: 'blur' }],
    };
};

export default defineComponent({
    name: 'dictModel',

    props: {
        visible: {
            type: Boolean,
            default: () => false,
        },
        title: {
            type: String,
        },
        loading: {
            type: Boolean,
            default: () => false,
        },
        detail: {
            type: Object,
        },
    },
    emits: ['submit', 'cancle'],
    setup(props, { emit }) {
        const { t } = useI18n();

        const showModal = computed(() => props.visible);

        const formState = reactive({
            detail: {
                typeName: '',
                id: null,
                type: 1,
                pCode: null,
            },
        });

        // 编辑时赋值
        watch(
            () => props.detail,
            (detail) => {
                formState.detail = Object.assign({}, formState.detail, detail);
            }
        );

        // 表单校验
        const rules = initRules(t);
        const formRef = ref();
        // 提交
        const onSubmit = () => {
            formRef.value.validate().then(() => {
                emit('submit', formState.detail);
            });
        };

        // 取消
        const handleCancle = () => {
            return emit('cancle');
        };

        return {
            formRef,
            showModal,
            ...toRefs(formState),
            t,
            rules,
            onSubmit,
            handleCancle,
        };
    },
});
</script>
<style lang="scss" scoped>
.dict-model {
    @include flexWrap;
    width: 100%;
    .ant-form-item {
        @include flex;
        width: 50%;
        margin-right: 0;
        padding-right: $width10;
        margin-bottom: $width8;
        :deep .ant-form-item-label {
            flex-basis: $formLabel;
        }
        :deep .ant-form-item-control-wrapper {
            flex: 1;
        }
        :deep .ant-form-item-children,
        :deep .ant-input-number {
            width: 100%;
        }
        &.full-width {
            width: 100%;
        }
    }
}
</style>
